package com.ayuku.retail.business.purchase;

import java.util.List;
import java.util.Map;

import com.ayuku.commons.AyukuDB;
import com.ayuku.retail.persistence.model.ItemPurchase;
import com.ayuku.retail.persistence.model.Purchase;

public class PurchaseImpl {

	public static List<Purchase> getList(String arg) throws Exception {
		List<Purchase> lst = AyukuDB.getPersist().readList(
				Purchase.class,
				"SELECT * FROM Purchase WHERE "
						+ "ucase(trx_code) LIKE ucase(?) "
						+ "or ucase(Supplier) LIKE ucase(?)",
				new Object[] { arg, arg });
		return lst;
	}

	public static List<Map<String, Object>> getMapList(String arg)
			throws Exception {
		List<Map<String, Object>> lst = AyukuDB.getPersist().readMapList(arg);
		return lst;
	}

	public static Purchase getById(String key) throws Exception {
		Purchase obj = (Purchase) AyukuDB.getPersist().readByPrimaryKey(
				Purchase.class, new Object[] { key });
		return obj;
	}

	@SuppressWarnings("unchecked")
	public static int add(Map<String, Object> mp) throws Exception {
		Purchase prc  = (Purchase) mp.get("hdr");
		int n = AyukuDB.getPersist().insert(prc);
		
		List<ItemPurchase> lst = (List<ItemPurchase>)mp.get("dtls");
		if (lst != null && lst.size() > 0) {
			for (int i = 0; i < lst.size(); i++) {
				ItemPurchase item = lst.get(i);
			
				item.setTrxCode(prc.getTrxCode());
				item.setCreatedBy(prc.getCreatedBy());
				item.setCreatedDate(prc.getCreatedDate());
				item.setModifiedBy(prc.getModifiedBy());
				item.setModifiedDate(prc.getModifiedDate());				
				n += AyukuDB.getPersist().insert(item);
			}
		}	
		return n;
	}

	public static int update(Purchase obj) throws Exception {
		return AyukuDB.getPersist().update(obj);
	}

	public static int delete(String key) throws Exception {
		int n = AyukuDB.getPersist().executeUpdate(
				"delete from Purchase where trim(trx_code)=?",
				new Object[] { key.trim() });
		return n;
	}

	public static int delete(List<String> ids) throws Exception {
		int n = 0;
		try {
			AyukuDB.getPersist().setAutoCommit(false);
			for (int j = 0; j < ids.size(); j++) {
				String key = ids.get(j);
				n += delete(key);
			}
			AyukuDB.getPersist().commit();
		} catch (Exception e) {
			e.printStackTrace();
			AyukuDB.getPersist().rollback();
			throw new Exception();
		} finally {
			AyukuDB.getPersist().setAutoCommit(true);
		}
		return n;
	}

}
